<?php

/**
 *  +---------------------------------------------------------------------- 
 *  | 文件功能：站点设置/配置相关功能控制器
 *  +---------------------------------------------------------------------- 
 *  | Copyright (c) 2022~2024 https://www.huihuiv.com All rights reserved.
 *  +---------------------------------------------------------------------- 
 *  | Create At: 2024年02月26日 18:06:36
 *  +---------------------------------------------------------------------- 
 *  | Author: 半壶水 <star@cqshanwen.com>
 *  +---------------------------------------------------------------------- 
 */

namespace App\Http\Controllers\Api;

use App\Interface\CurdController;
use App\Librarys\Message;
use App\Models\SettingModel;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class SettingController extends BaseController implements CurdController
{
    private Request $request;
    private Model $settingModel;

    public function __construct(Request $request, SettingModel $settingModel)
    {
        $this->request = $request;
        $this->settingModel = $settingModel;
    }

    public function create()
    {
        // 获取配置的操作flag
        $flag = $this->request->flag;

        // switch 匹配出理
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'create':
                // 获取必要参数数据
                $settingInfo['name'] = $this->request->name;
                $settingInfo['content'] = json_encode($this->request->content);

                // 判断操作行为
                if ($settingInfo['name'] == '') {
                    return Message::show(false, '无法定义的设置字段');
                }
                if ($this->settingModel->where(['name' => $settingInfo['name']])->exists()) { // 存在设置字段数据，更新
                    // 验证
                    $validate = Validator::make($settingInfo, [
                        'name' => 'required',
                        'content' => 'required'
                    ], [
                        'name.required' => '设置项名称不能为空',
                        'content.required' => '设置项内容不能为空'
                    ]);

                    // 判断是否验证成功
                    if ($validate->fails()) {
                        // 验证失败
                        return Message::show(false, $validate->errors()->first());
                    }

                    // 验证成功,开启事务
                    DB::beginTransaction();
                    try {
                        // 修改数据库
                        $this->settingModel->where(['name' => $settingInfo['name']])->update($settingInfo);

                        // 提交事务
                        DB::commit();
                        return Message::show(true, '站点配置信息修改成功');
                    } catch (Exception $error) {
                        // 事务回滚
                        DB::rollBack();
                        return Message::show(false, $error->getMessage());
                    }
                } else { // 不存在设置字段数据，新增
                    // 验证
                    $validate = Validator::make($settingInfo, [
                        'name' => 'required|unique:sw_setting',
                        'content' => 'required'
                    ], [
                        'name.required' => '设置项名称不能为空',
                        'name.unique' => '该设置项已经存在',
                        'content.required' => '设置项内容不能为空'
                    ]);

                    // 判断是否验证成功
                    if ($validate->fails()) {
                        // 验证失败
                        return Message::show(false, $validate->errors()->first());
                    }

                    // 验证成功,开启事务
                    DB::beginTransaction();
                    try {
                        // 写入数据库
                        $this->settingModel->create($settingInfo);

                        // 提交事务
                        DB::commit();
                        return Message::show(true, '保存成功');
                    } catch (Exception $error) {
                        // 事务回滚
                        DB::rollBack();
                        return Message::show(false, $error->getMessage());
                    }
                }


                break;
            case 'update':
                // 更新
                break;
        }
    }

    public function query(): JsonResponse
    {
        // 获取查询类型
        $flag = $this->request->flag;
        // 匹配查询类型
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'basic': // 获取站点基础信息
                // 查询数据
                $basicInfo = $this->settingModel->where(['name' => 'basic'])->first();
                // 判断数据
                if (empty($basicInfo)) {
                    return Message::show(false, '当前设置未初始化，请在系统设置中完成初始化内容');
                }
                return Message::show(true, '获取成功', $basicInfo);
                break;
            case 'all': // 获取全部非敏感配置信息
                // 查询数据
                $allInfo = $this->settingModel->get();
                // 判断数据
                if (empty($allInfo)) {
                    return Message::show(false, '当前站点无初始化信息，请前往站点配置完成初始化');
                }
                // 数据格式化，用于前端使用
                $allSettings = [];
                // 循环所有数据
                foreach ($allInfo as $key => $value) {
                    // 将当前item的值的name字段作为新字段数组索引，content字段作为新数组的值
                    $allSettings[$value['name']] = json_decode($value['content'], true);
                }
                return Message::show(true, '获取成功', $allSettings);
                break;
        }
    }
    public function delete()
    {
    }
}
